package 经典100题;

/**
 * 其他思路 找第k小的数
 */
public class 寻找两个正序数组的中位数 {
    public static  double findMedianSortedArrays(int[] nums1, int[] nums2) {

        //合并数组
        int[] nums = merge(nums1, nums2);

        return findMedianSortedArrays(nums);
    }

    public static int[] merge(int[] nums1, int[] nums2){
        if (nums1.length == 0 && nums2.length == 0){
            return nums1;
        }
        if (nums1.length == 0 && nums2.length != 0){
            return nums2;
        }
        if (nums2.length == 0 && nums1.length != 0){
            return nums1;
        }

        int totalLength = nums1.length + nums2.length;
        int[] newArray = new int[totalLength];

        int count = 0;
        int i = 0;
        int j = 0;
        while(count != totalLength){
            if (i == nums1.length){
                while( j != nums2.length){
                    newArray[count] = nums2[j];
                }
                break;
            }
            if (j == nums2.length){
                while( i != nums1.length){
                    newArray[count] = nums1[i];
                }
                break;
            }

            if (nums1[i] <= nums2[j]){
                newArray[count] = nums1[i++];
            }else{
                newArray[count] = nums1[j++];
            }
            count++;
        }
        return newArray;

    }
    public static double findMedianSortedArrays(int[] nums) {
        if (nums.length == 0){
            return 0;
        }
        if (nums.length == 1){
            return  nums[0];
        }
        int mid = (nums.length - 1) / 2;
        if (nums.length % 2 == 0){
            return (nums[mid] + nums[mid + 1]) / 2;
        }else{
            return nums[mid];
        }
    }
}
